﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Threading;
using System.Collections.Specialized;
using DirectoryViewModels;
using System.Threading;
using BrainTechLLC.FileMaintenance;
using BrainTechLLC.WPF;
using DragDropLibrary;

using System.ComponentModel;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC.FolderExplorer
{
    /// <summary>
    /// Interaction logic for FolderExplorerControl.xaml
    /// </summary>
    public partial class FolderExplorerControl : UserControl
    {
        protected bool _shiftDown;
        protected bool _controlDown;

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (treeView1.SelectedItem != null)
            {
                FolderViewModel folder = treeView1.SelectedItem as FolderViewModel;

                if (e.Key == Key.Delete)
                {
                    MessageBoxResult result = MessageBoxResult.Yes;

                    if ((e.KeyboardDevice.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift)
                    {
                        result = MessageBox.Show("Delete directory " + folder.FullPath + "?", "Delete Directory?", MessageBoxButton.YesNo);
                    }

                    if (result == MessageBoxResult.Yes)
                    {
                        DirectoryInfo di = new DirectoryInfo(folder.FullPath);
                        FileWorker.SetFileAttribute(di, FileAttributes.Normal);
                        Directory.Delete(folder.FullPath, true);
                        folder.Parent.RefreshSubfolders();
                    }
                }
            }

            HandleKey(e, true);
        }

        private void UserControl_KeyUp(object sender, KeyEventArgs e)
        {
            HandleKey(e, false);
        }

        public List<FolderViewModel> GetSelectedFolders()
        {
            return (from folder in RootFolder.GetAllFoldersInMemory() where folder.IsSelected == true select folder).ToList();
        }

        private void HandleKey(KeyEventArgs e, bool down)
        {
            FolderViewModel lastFolder = _lastSelected == null ? null : _lastSelected.Tag as FolderViewModel;
            
            if (lastFolder != null && lastFolder.IsEditMode)
            {
                return;
            }

            if (e.Key == Key.Enter)
            {
                this.tvRoot.Focus();
            }
            else if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
            {
                _shiftDown = down;
                e.Handled = true;
            }
            else if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                _controlDown = down;
                e.Handled = true;
            }
            else if (down)
            {
                if (e.Key == Key.Space)
                {
                    int idx = FindIndex(_lastSelected);
                    var tvi = _TreeViewItems[idx];
                    FolderViewModel folder = tvi.Tag as FolderViewModel;
                    GetSelectedFolders().ForEach(f => f.IsChecked = !folder.IsChecked);
                    e.Handled = true;
                }
                else if (e.Key == Key.F2)
                {
                    RenameFolder(lastFolder);
                    e.Handled = true;
                }
                else if (e.Key == Key.Down)
                {
                    int idx = FindIndex(_lastSelected);
                    DoSelection(idx, 1);
                    e.Handled = true;
                }
                else if (e.Key == Key.Up)
                {
                    int idx = FindIndex(_lastSelected);
                    DoSelection(idx, -1);
                    e.Handled = true;
                }
                else if (e.Key == Key.PageUp || e.Key == Key.NumPad9)
                {
                    int items = (int)Math.Floor(treeView1.ActualHeight / _TreeViewItems[0].ActualHeight);
                    int idx = FindIndex(_lastSelected);
                    DoSelection(idx, -items);
                    e.Handled = true;
                }
                else if (e.Key == Key.PageDown || e.Key == Key.NumPad3)
                {
                    int items = (int)Math.Floor(treeView1.ActualHeight / _TreeViewItems[0].ActualHeight);
                    int idx = FindIndex(_lastSelected);
                    DoSelection(idx, items);
                    e.Handled = true;
                }
                else if (e.Key == Key.Left)
                {
                    var folders = GetSelectedFolders();
                    folders.Add(lastFolder);
                    for (int n = 0; n < folders.Count; n++)
                    {
                        var fold = folders[n];
                        var parentFolder = fold.Parent;
                        if (parentFolder != null)
                        {
                            int idx = FindIndex(parentFolder);
                            if (idx != -1)
                            {
                                var tvi = _TreeViewItems[idx];
                                ChangeSelectedState(tvi, true, false);
                            }
                        }
                        fold.IsExpanded = false;
                    }
                    e.Handled = true;
                }
                else if (e.Key == Key.Right)
                {
                    var folders = GetSelectedFolders();
                    folders.Add(lastFolder);
                    for (int n = 0; n < folders.Count; n++)
                    {
                        var fold = folders[n];
                        var subFolders = fold.SubFolders;
                        if (subFolders != null && subFolders.Count > 0)
                        {
                            fold.IsExpanded = true;
                        }
                    }
                    e.Handled = true;
                }
            }
        }

        private void DoSelection(int idx, int increment)
        {
        TryAgain:
            idx += increment;

            if (idx < 0)
            {
                idx = 0;
            }

            if (idx >= _TreeViewItems.Count)
            {
                idx = _TreeViewItems.Count - 1;
            }

            if (idx < _TreeViewItems.Count && idx >= 0)
            {
                var tvi = _TreeViewItems[idx];
                FolderViewModel folder = tvi.Tag as FolderViewModel;
                if (folder.Parent != null && !folder.Parent.IsExpanded)
                {
                    goto TryAgain;
                }
                ChangeSelectedState(tvi, !folder.IsSelected, false);
            }
        }

        private void treeView1_KeyUp(object sender, KeyEventArgs e)
        {
            HandleKey(e, false);
        }

        private void txt_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;
            FolderViewModel f = tb.Tag as FolderViewModel;

            if (e.Key == Key.Escape)
            {
                tb.Text = f.Name;
                this.tvRoot.Focus();
                e.Handled = true;
            }
            else
            {
                HandleKey(e, true);
            }
        }

        public int FindIndex(TreeViewItem tvi)
        {
            for (int n = 0; n < _TreeViewItems.Count; n++)
            {
                if (_TreeViewItems[n] == tvi)
                {
                    return n;
                }
            }
            return -1;
        }

        private void treeView1_KeyDown(object sender, KeyEventArgs e)
        {
            HandleKey(e, true);
        }

        private void tvRoot_KeyDown(object sender, KeyEventArgs e)
        {
            HandleKey(e, true);
        }

        private void tvRoot_KeyUp(object sender, KeyEventArgs e)
        {
            HandleKey(e, false);
        }

        private void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            HandleKey(e, true);
        }

        private void Grid_KeyUp(object sender, KeyEventArgs e)
        {
            HandleKey(e, false);
        }

        private void tvRoot_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            HandleKey(e, true);
        }


    }
}